package com.github.chirspan.xaas.core.db.jdbc;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.DbRuntimeException;
import cn.hutool.db.DbUtil;
import cn.hutool.db.meta.MetaUtil;
import cn.hutool.db.meta.Table;
import cn.hutool.db.meta.TableType;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * *******description*******
 * <p>
 * *************************
 *
 * @author chenpan
 * @date 2020/7/24 13:56
 */
@Slf4j
public class JdbcMetaUtils {

    public static List<Table> getTablesMeta(DataSource ds, String schema, String tableName, TableType... types) {
        final List<Table> tables = new ArrayList<>();
        Connection conn = null;
        try {
            conn = ds.getConnection();
           /* if(conn instanceof OracleConnection){
                ((OracleConnection)conn).setRemarksReporting(true);
            }*/
            // catalog和schema获取失败默认使用null代替
            String catalog = MetaUtil.getCataLog(conn);
            if (null == schema) {
                schema = MetaUtil.getSchema(conn);
            }
            final DatabaseMetaData metaData = conn.getMetaData();
            try (ResultSet rs = metaData.getTables(catalog, schema, tableName, Convert.toStrArray(types))) {
                if (null != rs) {
                    Table table;
                    String tableNa;
                    while (rs.next()) {
                        tableNa = rs.getString("TABLE_NAME");
                        if (StrUtil.isNotBlank(tableNa)) {
                            table = Table.create(tableNa);
                            table.setComment(rs.getString("REMARKS"));
                            tables.add(table);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("Get tables error:", e);
            throw new DbRuntimeException("Get tables error!", e);
        } finally {
            DbUtil.close(conn);
        }
        return tables;
    }
}
